//
//  GFSearchViewController.m
//  Qyer
//
//  Created by dlios on 15/10/26.
//  Copyright (c) 2015年 GF. All rights reserved.
//

#import "GFSearchViewController.h"

@interface GFSearchViewController ()<GFRmViewDelegate>
{
    UIButton *cannelButton;
}
@end

@implementation GFSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.navigationController.navigationBar.hidden = YES;
    
//    NavView *view = [[NavView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64 * HEIGHT)];
//    [view setBackgroundColor:NAVBAR_COLOR];
//    [self.view addSubview:view];
    
    _tableArray = [NSMutableArray array];
    _field = [[UITextField alloc] initWithFrame:CGRectMake(70 * WIDTH, 5 * HEIGHT, SCREEN_WIDTH - 150 * WIDTH, 30 * HEIGHT)];
    [_field setPlaceholder:@"🔍请输入您要搜索的内容"];
    [_field setDelegate:self];
    [_field.layer setCornerRadius:5.];
    [_field setKeyboardType:UIKeyboardTypeDefault];
    [_field setReturnKeyType:UIReturnKeyGo];
    [_field setClearButtonMode:UITextFieldViewModeAlways];
    [_field.layer setBorderWidth:.5];
    [_field.layer setBorderColor:[UIColor greenColor].CGColor];
    [_field setBackgroundColor:NAVBAR_COLOR];
    [self.navigationController.navigationBar addSubview:_field];
    
    _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [_searchView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:_searchView];
    
    UILabel *rLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 64 * HEIGHT, SCREEN_WIDTH, 30 * HEIGHT)];
    [rLable setText:@"    热门搜索"];
    [rLable setTextColor:[NightMode shareNightModeHandle].wordColor];
    [rLable setFont:[UIFont boldSystemFontOfSize:WIDTH * 16.]];
    [_searchView addSubview:rLable];
    
    GFRmView *rView = [[GFRmView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 110 * HEIGHT)];
    [rView setDelegate:self];
    [rView setBackgroundColor:NAVBAR_COLOR];
    
    cannelButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 81 * WIDTH, 5 * HEIGHT, 40 * WIDTH, 30 * HEIGHT)];
    [cannelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cannelButton.layer setCornerRadius:3.];
    [cannelButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [cannelButton.layer setBorderWidth:1.5];
    [cannelButton.layer setBorderColor:[UIColor greenColor].CGColor]; 
//    [cannelButton setTitleColor:[NightMode shareNightModeHandle].wordColor forState:UIControlStateNormal];
    [cannelButton addTarget:self action:@selector(cannelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:cannelButton];
    _table = [[UITableView alloc] initWithFrame:CGRectMake(0, 94 * HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 142 * HEIGHT) style:UITableViewStylePlain];
    [_table setDelegate:self];
    [_table setDataSource:self];
    [_table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_table setBounces:NO];
    [_table setTableHeaderView:rView];
    [_searchView addSubview:_table];
}

- (void)getString:(NSString *)string{
    [_tableArray removeAllObjects];
    [cannelButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    _field.text = string;
    [self getAfn];
    [_field resignFirstResponder];
}

- (void)cannelButtonClick: (UIButton *)sender{
    [_tableArray removeAllObjects];
    [cannelButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    _field.text = nil;
    [_table reloadData];
}

- (void)getAfn{
    NSString *comString = [NSString stringWithFormat:@"http://open.qyer.com/qyer/search/index?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=868842022014563&track_app_version=6.8.1&track_app_channel=xiaomi&track_device_info=hermes&track_os=Android5.0.2&app_installtime=1444898310285&lat=38.883539&lon=121.544848&type=thread&keyword=%@&count=40&page=1", _field.text];
    NSLog(@"comString == %@", comString);
    [AFN getdataWithString:comString block:^(id block) {
        for (NSDictionary *dic in [[block objectForKey:@"data"]objectForKey:@"entry"]) {
            GFSearchModel *model = [GFSearchModel modelWithDictionary:dic];
            [_tableArray addObject:model];
        }
        if (_tableArray.count == 0) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"没有您要搜索的数据" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
            [_table reloadData];
    } BLOCK:^(id BLOCK) {
        
    }];
}

- (void)viewDidDisappear:(BOOL)animated{
    [_field removeFromSuperview];
    [cannelButton removeFromSuperview];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [_tableArray removeAllObjects];
    [cannelButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_table reloadData];
    [self getAfn];
    [_field resignFirstResponder];
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    [UIView animateWithDuration:1. animations:^{
        [_searchView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 112 * HEIGHT)];

    }];
    [cannelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    [cannelButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_tableArray removeAllObjects];
    [_table reloadData];
    return YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _tableArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90 * HEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *guoFeng = @"cell";
    GFSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:guoFeng];
    if (!cell) {
        cell = [[GFSearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:guoFeng];
    }
    GFSearchModel *model = [_tableArray objectAtIndex:indexPath.row];
    [cell getSearchModel:model];
    
    NSMutableString *string = [[NSMutableString alloc] initWithString:model.title];
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange titleRange = [string rangeOfString:_field.text];
    
    [attributeString addAttribute:NSForegroundColorAttributeName value:NAVBAR_COLOR range:titleRange];
    cell.lable.attributedText = attributeString;
    cell.accessoryType = 1;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    GFSearchModel *model = [_tableArray objectAtIndex:indexPath.row];
    WebViewController *web = [[WebViewController alloc]init];
    web.webString = model.view_url;
    [self.navigationController pushViewController:web animated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
